// 工业生产预测项目答辩文档交互功能

// 等待文档加载完成
document.addEventListener('DOMContentLoaded', function() {
    // 添加淡入效果
    const container = document.querySelector('.container');
    if (container) {
        container.classList.add('fade-in');
    }
    
    // 添加平滑滚动
    setupSmoothScroll();
    
    // 添加目录导航
    createTableOfContents();
    
    // 为图表添加点击放大功能
    setupImageZoom();
    
    // 监听滚动位置以高亮当前章节
    window.addEventListener('scroll', highlightCurrentSection);
    
    // 添加返回顶部按钮
    createBackToTopButton();
    
    // 高亮代码块
    highlightCodeBlocks();
    
    // 初始化所有功能
    initBackToTop();
    initScrollAnimation();
    initCollapsible();
    initProgressBar();
    setCodeLanguageTags();
    initStageDots();
    initCharts();
    
    // 激活SVG动画
    setTimeout(initSvgAnimation, 500);
    
    // 初始化侧边栏
    initSidebar();
});

// 平滑滚动功能
function setupSmoothScroll() {
    document.querySelectorAll('a[href^="#"]').forEach(anchor => {
        anchor.addEventListener('click', function(e) {
            e.preventDefault();
            
            const targetId = this.getAttribute('href');
            const targetElement = document.querySelector(targetId);
            
            if (targetElement) {
                window.scrollTo({
                    top: targetElement.offsetTop - 70,
                    behavior: 'smooth'
                });
            }
        });
    });
}

// 创建目录导航
function createTableOfContents() {
    const container = document.querySelector('.container');
    if (!container) return;
    
    // 创建导航元素
    const nav = document.createElement('div');
    nav.className = 'nav';
    
    const ul = document.createElement('ul');
    nav.appendChild(ul);
    
    // 查找所有h2标题
    const headings = container.querySelectorAll('h2');
    
    headings.forEach((heading, index) => {
        // 为每个标题添加ID
        if (!heading.id) {
            heading.id = 'section-' + index;
        }
        
        // 创建导航项
        const li = document.createElement('li');
        const a = document.createElement('a');
        a.href = '#' + heading.id;
        a.textContent = heading.textContent;
        li.appendChild(a);
        ul.appendChild(li);
    });
    
    // 插入导航到文档
    container.parentNode.insertBefore(nav, container);
}

// 图像放大功能
function setupImageZoom() {
    document.querySelectorAll('.chart img').forEach(img => {
        img.style.cursor = 'pointer';
        
        img.addEventListener('click', function() {
            // 创建遮罩层
            const overlay = document.createElement('div');
            overlay.style.position = 'fixed';
            overlay.style.top = '0';
            overlay.style.left = '0';
            overlay.style.width = '100%';
            overlay.style.height = '100%';
            overlay.style.backgroundColor = 'rgba(0,0,0,0.8)';
            overlay.style.display = 'flex';
            overlay.style.justifyContent = 'center';
            overlay.style.alignItems = 'center';
            overlay.style.zIndex = '1000';
            overlay.style.cursor = 'pointer';
            
            // 创建放大的图像
            const zoomedImg = document.createElement('img');
            zoomedImg.src = this.src;
            zoomedImg.style.maxWidth = '90%';
            zoomedImg.style.maxHeight = '90%';
            zoomedImg.style.border = '2px solid white';
            
            overlay.appendChild(zoomedImg);
            document.body.appendChild(overlay);
            
            // 点击关闭
            overlay.addEventListener('click', function() {
                document.body.removeChild(overlay);
            });
        });
    });
}

// 高亮当前章节
function highlightCurrentSection() {
    const scrollPosition = window.scrollY;
    
    // 获取所有章节
    const sections = document.querySelectorAll('h2');
    const navLinks = document.querySelectorAll('.nav a');
    
    if (!sections.length || !navLinks.length) return;
    
    // 找出当前章节
    let currentSection = sections[0].id;
    
    sections.forEach(section => {
        if (section.offsetTop - 100 <= scrollPosition) {
            currentSection = section.id;
        }
    });
    
    // 清除所有高亮
    navLinks.forEach(link => {
        link.classList.remove('active');
    });
    
    // 高亮当前章节
    const activeLink = document.querySelector(`.nav a[href="#${currentSection}"]`);
    if (activeLink) {
        activeLink.classList.add('active');
    }
    
    // 显示或隐藏返回顶部按钮
    const backToTop = document.querySelector('.back-to-top');
    if (backToTop) {
        if (scrollPosition > 300) {
            backToTop.classList.add('visible');
        } else {
            backToTop.classList.remove('visible');
        }
    }
}

// 创建返回顶部按钮
function createBackToTopButton() {
    const backBtn = document.createElement('div');
    backBtn.className = 'back-to-top';
    backBtn.innerHTML = '<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M8 3L14 9L12.6 10.4L9 6.8L9 13L7 13L7 6.8L3.4 10.4L2 9L8 3Z" fill="white"/></svg>';
    
    document.body.appendChild(backBtn);
    
    backBtn.addEventListener('click', function() {
        window.scrollTo({
            top: 0,
            behavior: 'smooth'
        });
    });
}

// 代码高亮处理
function highlightCodeBlocks() {
    document.querySelectorAll('.code-block').forEach(block => {
        // 检查是否已经有pre元素
        if (!block.querySelector('pre')) {
            // 提取代码内容
            const codeContent = block.innerHTML;
            
            // 创建新的结构
            const preElement = document.createElement('pre');
            const codeElement = document.createElement('code');
            
            // 设置代码内容
            codeElement.innerHTML = formatPythonCode(codeContent);
            
            // 构建DOM结构
            preElement.appendChild(codeElement);
            block.innerHTML = '';
            block.appendChild(preElement);
        }
    });
}

// Python代码格式化
function formatPythonCode(code) {
    // 移除首尾的```python和```标记
    code = code.replace(/^```python\s*/, '').replace(/```\s*$/, '');
    
    // 移除HTML实体编码
    code = code.replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/&amp;/g, '&');
    
    // 关键字高亮
    const keywords = ['def', 'return', 'import', 'from', 'as', 'if', 'else', 'elif', 'for', 'while', 
                     'in', 'try', 'except', 'finally', 'with', 'class', 'lambda', 'print', 'and', 'or', 
                     'not', 'True', 'False', 'None', 'break', 'continue', 'pass', 'raise', 'assert'];
    
    // 创建正则表达式来匹配关键字（确保它们是完整的单词）
    const keywordRegex = new RegExp('\\b(' + keywords.join('|') + ')\\b', 'g');
    
    // 对代码应用高亮
    code = code
        // 保护字符串和注释免受其他替换的影响
        .replace(/(["'])(?:(?=(\\?))\2.)*?\1/g, match => `<span class="code-string">${match}</span>`) // 字符串
        .replace(/(#.*)$/gm, match => `<span class="code-comment">${match}</span>`) // 单行注释
        .replace(/\b(\d+(?:\.\d+)?)\b/g, match => `<span class="code-number">${match}</span>`) // 数字
        .replace(keywordRegex, match => `<span class="code-keyword">${match}</span>`) // 关键字
        .replace(/\b([A-Za-z_][A-Za-z0-9_]*)\s*\(/g, match => { // 函数调用
            const functionName = match.slice(0, -1); // 去掉最后的括号
            return `<span class="code-function">${functionName}</span>(`;
        });
    
    return code;
}

// 打印功能
function printDocument() {
    window.print();
}

// 导出为PDF（需要额外库支持）
function exportToPDF() {
    alert('PDF导出功能需要引入额外的库，如html2pdf.js');
}

// 提供全局访问点
window.presentationTools = {
    print: printDocument,
    exportPDF: exportToPDF
};

// 返回顶部按钮
function initBackToTop() {
    const backToTopButton = document.querySelector('.back-to-top');
    if (!backToTopButton) return;
    
    // 监听滚动事件
    window.addEventListener('scroll', function() {
        if (window.pageYOffset > 300) {
            backToTopButton.classList.add('visible');
        } else {
            backToTopButton.classList.remove('visible');
        }
    });
    
    // 点击返回顶部
    backToTopButton.addEventListener('click', function() {
        window.scrollTo({
            top: 0,
            behavior: 'smooth'
        });
    });
}

// 滚动动画
function initScrollAnimation() {
    const animatedElements = document.querySelectorAll('.step, .chart, .workflow');
    
    if ('IntersectionObserver' in window) {
        const observer = new IntersectionObserver((entries) => {
            entries.forEach(entry => {
                if (entry.isIntersecting) {
                    entry.target.classList.add('fade-in');
                    observer.unobserve(entry.target);
                }
            });
        }, {
            threshold: 0.1
        });
        
        animatedElements.forEach(element => {
            observer.observe(element);
        });
    } else {
        // 降级处理，对于不支持IntersectionObserver的浏览器
        animatedElements.forEach(element => {
            element.classList.add('fade-in');
        });
    }
}

// 滚动进度条
function initProgressBar() {
    // 创建进度条容器和进度条
    const progressContainer = document.createElement('div');
    progressContainer.className = 'progress-container';
    
    const progressBar = document.createElement('div');
    progressBar.className = 'progress-bar';
    
    progressContainer.appendChild(progressBar);
    document.body.appendChild(progressContainer);
    
    // 监听滚动更新进度条
    window.addEventListener('scroll', function() {
        const scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
        const height = document.documentElement.scrollHeight - document.documentElement.clientHeight;
        const scrolled = (scrollTop / height) * 100;
        progressBar.style.width = scrolled + '%';
    });
}

// 设置代码块的语言标签
function setCodeLanguageTags() {
    const codeBlocks = document.querySelectorAll('.code-block');
    
    codeBlocks.forEach(block => {
        // 检查代码内容推断语言
        const code = block.textContent.toLowerCase();
        
        if (code.includes('python') || code.includes('import ') || code.includes('def ')) {
            block.setAttribute('data-language', 'python');
        } else if (code.includes('select ') || code.includes('create table')) {
            block.setAttribute('data-language', 'sql');
        } else if (code.includes('<html') || code.includes('<div')) {
            block.setAttribute('data-language', 'html');
        } else if (code.includes('{') && code.includes('}') && (code.includes('":') || code.includes('":"'))) {
            block.setAttribute('data-language', 'json');
        }
    });
}

// 异烟酸收率预测模型应用实施方案 - 交互脚本

// 页面加载完成后初始化所有交互功能
document.addEventListener('DOMContentLoaded', function() {
    // 初始化图表
    initCharts();
    
    // 初始化回到顶部按钮
    initBackToTop();
    
    // 初始化滚动动画
    initScrollAnimation();
    
    // 初始化进度条
    initProgressBar();
    
    // 初始化代码块语言检测
    initCodeBlockLanguage();
    
    // 初始化阶段点
    initStageDots();
});

// 初始化回到顶部按钮
function initBackToTop() {
    // 创建回到顶部按钮
    const backToTop = document.createElement('div');
    backToTop.className = 'back-to-top';
    backToTop.innerHTML = '↑';
    document.body.appendChild(backToTop);
    
    // 监听滚动事件
    window.addEventListener('scroll', function() {
        if (window.pageYOffset > 300) {
            backToTop.classList.add('visible');
        } else {
            backToTop.classList.remove('visible');
        }
    });
    
    // 点击事件
    backToTop.addEventListener('click', function() {
        window.scrollTo({
            top: 0,
            behavior: 'smooth'
        });
    });
}

// 初始化滚动动画
function initScrollAnimation() {
    // 为适合动画的元素添加fade-in类
    const animElements = document.querySelectorAll('h2, h3, .visualization, .workflow .step, .card, .stats-container, .timeline-item');
    animElements.forEach(element => {
        element.classList.add('fade-in');
    });
    
    // 创建Intersection Observer
    const observer = new IntersectionObserver((entries) => {
        entries.forEach(entry => {
            if (entry.isIntersecting) {
                entry.target.classList.add('visible');
            }
        });
    }, {
        threshold: 0.1
    });
    
    // 观察所有带有fade-in类的元素
    document.querySelectorAll('.fade-in').forEach(element => {
        observer.observe(element);
    });
}

// 初始化进度条
function initProgressBar() {
    // 创建进度条容器
    const progressContainer = document.createElement('div');
    progressContainer.className = 'progress-container';
    
    // 创建进度条
    const progressBar = document.createElement('div');
    progressBar.className = 'progress-bar';
    
    // 添加到DOM
    progressContainer.appendChild(progressBar);
    document.body.appendChild(progressContainer);
    
    // 监听滚动事件更新进度条
    window.addEventListener('scroll', function() {
        const totalHeight = document.body.scrollHeight - window.innerHeight;
        const progress = (window.pageYOffset / totalHeight) * 100;
        progressBar.style.width = progress + '%';
    });
}

// 初始化代码块语言检测
function initCodeBlockLanguage() {
    document.querySelectorAll('pre code').forEach(block => {
        // 检测代码内容来判断语言类型
        const content = block.textContent;
        let language = '';
        
        if (content.includes('SELECT') || content.includes('CREATE TABLE')) {
            language = 'language-sql';
        } else if (content.includes('import') && (content.includes('pandas') || content.includes('numpy') || content.includes('sklearn'))) {
            language = 'language-python';
        } else if (content.includes('function') || content.includes('const') || content.includes('var')) {
            language = 'language-javascript';
        } else if (content.includes('<html>') || content.includes('<!DOCTYPE html>') || content.includes('<div>')) {
            language = 'language-html';
        } else if (content.includes('@media') || content.includes('margin:') || content.includes('padding:')) {
            language = 'language-css';
        } else if (content.includes('docker') || content.includes('apt-get') || content.includes('yum install')) {
            language = 'language-bash';
        } else {
            language = 'language-plaintext';
        }
        
        // 设置语言类
        block.className = language;
    });
}

// 初始化阶段点
function initStageDots() {
    // 为已完成的阶段添加效果
    const completedStages = document.querySelectorAll('.stage.completed');
    const activeStage = document.querySelector('.stage.active');
    
    // 添加动态效果
    if (completedStages.length > 0) {
        let delay = 0;
        completedStages.forEach(stage => {
            setTimeout(() => {
                stage.classList.add('animated');
            }, delay);
            delay += 300;
        });
    }
    
    if (activeStage) {
        setTimeout(() => {
            activeStage.classList.add('animated');
        }, completedStages.length * 300);
    }
}

// 初始化所有图表
function initCharts() {
    // 渲染数据流程图
    renderDataFlowChart();
    
    // 渲染其他图表...
    renderFeatureImportanceChart();
    renderAccuracyChart();
    renderROIChart();
    renderYieldTrendChart();
    
    // 添加模型参数影响图表
    if (document.querySelector('.feature-impact')) {
        // 为特征影响力条形图添加动画效果
        const featureBars = document.querySelectorAll('.feature-bar');
        featureBars.forEach(bar => {
            const originalWidth = bar.style.width;
            bar.style.width = '0';
            
            setTimeout(() => {
                bar.style.transition = 'width 1.5s ease-in-out';
                bar.style.width = originalWidth;
            }, 300);
        });
    }
}

// 渲染数据处理流程图
function renderDataFlowChart() {
    const dataFlowChart = document.getElementById('data-flow-chart');
    if (!dataFlowChart) return;
    
    // 使用echarts库渲染流程图
    const chart = echarts.init(dataFlowChart);
    
    const option = {
        title: {
            text: '数据处理流程',
            left: 'center',
            textStyle: {
                color: '#2c3e50'
            }
        },
        tooltip: {
            trigger: 'item',
            formatter: '{b}: {c}'
        },
        animationDurationUpdate: 1500,
        animationEasingUpdate: 'quinticInOut',
        color: ['#3498db', '#2ecc71', '#9b59b6', '#e67e22'],
        series: [
            {
                type: 'graph',
                layout: 'none',
                symbolSize: 50,
                roam: true,
                label: {
                    show: true
                },
                edgeSymbol: ['circle', 'arrow'],
                edgeSymbolSize: [4, 10],
                edgeLabel: {
                    fontSize: 12
                },
                data: [
                    {
                        name: '原始数据',
                        x: 100,
                        y: 200,
                        itemStyle: {
                            color: '#3498db'
                        }
                    },
                    {
                        name: '缺失值处理',
                        x: 250,
                        y: 200,
                        itemStyle: {
                            color: '#2ecc71'
                        }
                    },
                    {
                        name: '异常值处理',
                        x: 400,
                        y: 200,
                        itemStyle: {
                            color: '#2ecc71'
                        }
                    },
                    {
                        name: '格式标准化',
                        x: 550,
                        y: 200,
                        itemStyle: {
                            color: '#2ecc71'
                        }
                    },
                    {
                        name: '特征工程',
                        x: 700,
                        y: 200,
                        itemStyle: {
                            color: '#9b59b6'
                        }
                    },
                    {
                        name: '特征选择',
                        x: 850,
                        y: 200,
                        itemStyle: {
                            color: '#9b59b6'
                        }
                    },
                    {
                        name: '数据集划分',
                        x: 1000,
                        y: 200,
                        itemStyle: {
                            color: '#e67e22'
                        }
                    }
                ],
                links: [
                    {
                        source: '原始数据',
                        target: '缺失值处理',
                        label: {
                            show: true,
                            formatter: '5.2%缺失',
                            fontSize: 12
                        }
                    },
                    {
                        source: '缺失值处理',
                        target: '异常值处理',
                        label: {
                            show: true,
                            formatter: '填充',
                            fontSize: 12
                        }
                    },
                    {
                        source: '异常值处理',
                        target: '格式标准化',
                        label: {
                            show: true,
                            formatter: '3.8%异常',
                            fontSize: 12
                        }
                    },
                    {
                        source: '格式标准化',
                        target: '特征工程',
                        label: {
                            show: true,
                            formatter: '统一格式',
                            fontSize: 12
                        }
                    },
                    {
                        source: '特征工程',
                        target: '特征选择',
                        label: {
                            show: true,
                            formatter: '衍生特征',
                            fontSize: 12
                        }
                    },
                    {
                        source: '特征选择',
                        target: '数据集划分',
                        label: {
                            show: true,
                            formatter: '重要特征',
                            fontSize: 12
                        }
                    }
                ],
                lineStyle: {
                    opacity: 0.9,
                    width: 2,
                    curveness: 0
                }
            }
        ]
    };
    
    chart.setOption(option);
    
    // 窗口大小变化时自动调整图表大小
    window.addEventListener('resize', function() {
        chart.resize();
    });
}

// 渲染特征重要性图表
function renderFeatureImportanceChart() {
    const featureImportanceChart = document.getElementById('feature-importance-chart');
    if (!featureImportanceChart) return;
    
    const chart = echarts.init(featureImportanceChart);
    
    const option = {
        tooltip: {
            trigger: 'axis',
            axisPointer: { type: 'shadow' }
        },
        grid: { 
            left: '3%', 
            right: '4%', 
            bottom: '3%', 
            containLabel: true 
        },
        xAxis: {
            type: 'value',
            name: '重要性得分',
            nameLocation: 'middle',
            nameGap: 30
        },
        yAxis: {
            type: 'category',
            data: ['物料配比', '反应时间', 'pH值', '水用量', '反应温度', '压力', '搅拌速度', '物料纯度', '催化剂浓度'],
            axisLabel: {
                fontSize: 12,
                formatter: function(value) {
                    return value.length > 10 ? value.substring(0, 10) + '...' : value;
                }
            }
        },
        series: [{
            name: '特征重要性',
            type: 'bar',
            data: [0.285, 0.213, 0.157, 0.122, 0.094, 0.058, 0.036, 0.022, 0.013],
            itemStyle: {
                color: function(params) {
                    const colorList = [
                        '#c23531', '#2f4554', '#61a0a8', '#d48265', 
                        '#91c7ae', '#749f83', '#ca8622', '#bda29a', '#6e7074'
                    ];
                    return colorList[params.dataIndex];
                }
            },
            label: {
                show: true,
                position: 'right',
                formatter: '{c}'
            }
        }]
    };
    
    chart.setOption(option);
    
    // 窗口大小变化时自动调整图表大小
    window.addEventListener('resize', function() {
        chart.resize();
    });
}

// 渲染预测精度对比图表
function renderAccuracyChart() {
    const accuracyChart = document.getElementById('accuracy-chart');
    if (!accuracyChart) return;
    
    const chart = echarts.init(accuracyChart);
    
    // 生成模拟数据
    const data = [];
    const predictions = [];
    const actuals = [];
    
    for (let i = 0; i < 50; i++) {
        const base = Math.random() * 0.1 + 0.8; // 收率值范围在0.8-0.9之间
        const actual = base;
        // 预测值有一定偏差，大部分在±2%范围内
        const pred = base + (Math.random() - 0.5) * 0.04;
        
        data.push([i, actual, pred]);
        actuals.push([i, actual]);
        predictions.push([i, pred]);
    }
    
    const option = {
        title: {
            text: '异烟酸收率预测与实际值对比',
            left: 'center',
            textStyle: {
                fontSize: 16
            }
        },
        tooltip: {
            trigger: 'axis',
            formatter: function (params) {
                const idx = params[0].dataIndex;
                const actual = data[idx][1].toFixed(4);
                const pred = data[idx][2].toFixed(4);
                const diff = (Math.abs(actual - pred) / actual * 100).toFixed(2);
                return `样本 ${idx}<br/>实际值: ${actual}<br/>预测值: ${pred}<br/>偏差: ${diff}%`;
            }
        },
        legend: {
            data: ['实际收率', '预测收率'],
            top: 30
        },
        grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
        },
        xAxis: {
            type: 'value',
            name: '样本序号',
            nameLocation: 'middle',
            nameGap: 30
        },
        yAxis: {
            type: 'value',
            name: '收率',
            nameLocation: 'middle',
            nameGap: 30,
            min: 0.75,
            max: 0.95
        },
        series: [
            {
                name: '实际收率',
                type: 'scatter',
                data: actuals,
                symbolSize: 10,
                itemStyle: {
                    color: '#c23531'
                }
            },
            {
                name: '预测收率',
                type: 'scatter',
                data: predictions,
                symbolSize: 10,
                itemStyle: {
                    color: '#2f4554'
                }
            },
            {
                name: '理想预测线',
                type: 'line',
                data: [[0, 0.75], [50, 0.95]],
                symbol: 'none',
                lineStyle: {
                    color: '#91c7ae',
                    type: 'dashed'
                }
            }
        ]
    };
    
    chart.setOption(option);
    
    // 窗口大小变化时自动调整图表大小
    window.addEventListener('resize', function() {
        chart.resize();
    });
}

// 渲染ROI图表
function renderROIChart() {
    const roiChart = document.getElementById('roi-chart');
    if (!roiChart) return;
    
    const chart = echarts.init(roiChart);
    
    const option = {
        title: {
            text: '项目投资回报分析',
            left: 'center'
        },
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'shadow'
            },
            formatter: function(params) {
                const data = params[0];
                if (data.seriesName === '累计收益') {
                    return `${data.name}: ${data.value} 万元`;
                } else {
                    return `${data.name}<br/>${data.seriesName}: ${data.value} 万元`;
                }
            }
        },
        legend: {
            data: ['投资成本', '年收益', '累计收益'],
            top: 30
        },
        grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
        },
        xAxis: {
            type: 'category',
            data: ['初始', '第一年', '第二年', '第三年', '第四年', '第五年']
        },
        yAxis: {
            type: 'value',
            name: '金额（万元）'
        },
        series: [
            {
                name: '投资成本',
                type: 'bar',
                stack: 'total',
                label: {
                    show: true,
                    position: 'inside'
                },
                emphasis: {
                    focus: 'series'
                },
                data: [120, 0, 0, 0, 0, 0]
            },
            {
                name: '年收益',
                type: 'bar',
                stack: 'total',
                label: {
                    show: true,
                    position: 'inside'
                },
                emphasis: {
                    focus: 'series'
                },
                data: [0, 45, 55, 65, 65, 70]
            },
            {
                name: '累计收益',
                type: 'line',
                symbol: 'circle',
                symbolSize: 8,
                label: {
                    show: true,
                    position: 'top',
                    formatter: '{c} 万元'
                },
                data: [-120, -75, -20, 45, 110, 180]
            }
        ]
    };
    
    chart.setOption(option);
    
    // 窗口大小变化时自动调整图表大小
    window.addEventListener('resize', function() {
        chart.resize();
    });
}

// 渲染收率趋势图表
function renderYieldTrendChart() {
    const yieldTrendChart = document.getElementById('yield-trend-chart');
    if (!yieldTrendChart) return;
    
    const chart = echarts.init(yieldTrendChart);
    
    // 模拟数据：优化前后的收率
    const beforeData = [];
    const afterData = [];
    const xAxisData = [];
    
    for (let i = 1; i <= 20; i++) {
        xAxisData.push('批次' + i);
        beforeData.push((Math.random() * 0.05 + 0.85).toFixed(3));
        afterData.push((Math.random() * 0.03 + 0.90).toFixed(3));
    }
    
    const option = {
        title: {
            text: '模型应用前后收率对比',
            left: 'center'
        },
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'cross',
                crossStyle: {
                    color: '#999'
                }
            }
        },
        legend: {
            data: ['优化前收率', '优化后收率', '提升百分比'],
            top: 30
        },
        grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
        },
        xAxis: [
            {
                type: 'category',
                data: xAxisData,
                axisPointer: {
                    type: 'shadow'
                }
            }
        ],
        yAxis: [
            {
                type: 'value',
                name: '收率',
                min: 0.8,
                max: 1.0,
                interval: 0.05,
                axisLabel: {
                    formatter: '{value}'
                }
            },
            {
                type: 'value',
                name: '提升百分比',
                min: 0,
                max: 10,
                interval: 2,
                axisLabel: {
                    formatter: '{value}%'
                }
            }
        ],
        series: [
            {
                name: '优化前收率',
                type: 'bar',
                data: beforeData
            },
            {
                name: '优化后收率',
                type: 'bar',
                data: afterData
            },
            {
                name: '提升百分比',
                type: 'line',
                yAxisIndex: 1,
                data: beforeData.map((before, index) => {
                    return (((afterData[index] - before) / before) * 100).toFixed(1);
                })
            }
        ]
    };
    
    chart.setOption(option);
    
    // 窗口大小变化时自动调整图表大小
    window.addEventListener('resize', function() {
        chart.resize();
    });
}

// 添加系统架构SVG动画效果
function initSvgAnimation() {
    // 获取SVG元素
    const svgElements = document.querySelectorAll('.system-architecture svg');
    
    svgElements.forEach(svg => {
        // 添加淡入效果
        const layers = svg.querySelectorAll('rect[rx="8"]');
        layers.forEach((layer, index) => {
            layer.style.opacity = 0;
            setTimeout(() => {
                layer.style.transition = 'opacity 0.5s ease';
                layer.style.opacity = 1;
            }, 300 * index);
        });
        
        // 添加组件淡入效果
        const components = svg.querySelectorAll('.component');
        components.forEach((component, index) => {
            component.style.opacity = 0;
            setTimeout(() => {
                component.style.transition = 'opacity 0.3s ease, transform 0.3s ease';
                component.style.opacity = 1;
                component.style.transform = 'translateY(0)';
            }, 1000 + 100 * index);
        });
        
        // 添加文字淡入效果
        const texts = svg.querySelectorAll('.layer-title, .component-text');
        texts.forEach((text, index) => {
            text.style.opacity = 0;
            setTimeout(() => {
                text.style.transition = 'opacity 0.5s ease';
                text.style.opacity = 1;
            }, 1500 + 100 * index);
        });
        
        // 添加连接线动画
        const arrows = svg.querySelectorAll('.arrow');
        arrows.forEach((arrow, index) => {
            const length = arrow.getTotalLength();
            arrow.style.strokeDasharray = length;
            arrow.style.strokeDashoffset = length;
            setTimeout(() => {
                arrow.style.transition = 'stroke-dashoffset 1s ease-in-out';
                arrow.style.strokeDashoffset = 0;
            }, 2000 + 500 * index);
        });
    });
    
    // 为ID为svg-fallback的SVG添加同样的动画
    const svgFallback = document.getElementById('svg-fallback');
    if (svgFallback) {
        const svg = svgFallback.querySelector('svg');
        if (svg) {
            // 添加淡入效果
            const rects = svg.querySelectorAll('rect[rx]');
            rects.forEach((rect, index) => {
                rect.style.opacity = 0;
                setTimeout(() => {
                    rect.style.transition = 'opacity 0.5s ease';
                    rect.style.opacity = 1;
                }, 300 * index);
            });
            
            // 添加文字淡入效果
            const texts = svg.querySelectorAll('text');
            texts.forEach((text, index) => {
                text.style.opacity = 0;
                setTimeout(() => {
                    text.style.transition = 'opacity 0.5s ease';
                    text.style.opacity = 1;
                }, 1500 + 100 * index);
            });
            
            // 添加连接线动画
            const paths = svg.querySelectorAll('path');
            paths.forEach((path, index) => {
                if (path.getTotalLength) {
                    const length = path.getTotalLength();
                    path.style.strokeDasharray = length;
                    path.style.strokeDashoffset = length;
                    setTimeout(() => {
                        path.style.transition = 'stroke-dashoffset 1s ease-in-out';
                        path.style.strokeDashoffset = 0;
                    }, 2000 + 500 * index);
                }
            });
        }
    }
}

// 侧边栏功能
function initSidebar() {
    const sidebar = document.getElementById('sidebar');
    const sidebarToggle = document.getElementById('sidebarToggle');
    const mainContent = document.getElementById('mainContent');
    const mobileNavToggle = document.getElementById('mobileNavToggle');
    const submenuItems = document.querySelectorAll('.sidebar-nav-item.has-submenu');
    
    // 检查URL中的锚点，如果存在则滚动到对应位置
    function checkUrlHash() {
        const hash = window.location.hash;
        if (hash && hash !== '') {
            const targetElement = document.querySelector(hash);
            if (targetElement) {
                setTimeout(() => {
                    window.scrollTo({
                        top: targetElement.offsetTop - 70,
                        behavior: 'smooth'
                    });
                    
                    // 更新侧边栏状态
                    updateSidebarActiveState();
                }, 300);
            }
        } else {
            // 如果没有锚点，则默认更新侧边栏状态
            updateSidebarActiveState();
        }
    }
    
    // 侧边栏收缩/展开功能
    if (sidebarToggle) {
        sidebarToggle.addEventListener('click', function() {
            sidebar.classList.toggle('collapsed');
            mainContent.classList.toggle('expanded');
            
            // 更改图标方向
            const icon = this.querySelector('i');
            if (sidebar.classList.contains('collapsed')) {
                icon.classList.remove('fa-chevron-left');
                icon.classList.add('fa-chevron-right');
            } else {
                icon.classList.remove('fa-chevron-right');
                icon.classList.add('fa-chevron-left');
            }
        });
    }
    
    // 移动端导航按钮功能
    if (mobileNavToggle) {
        mobileNavToggle.addEventListener('click', function() {
            sidebar.classList.toggle('mobile-expanded');
            
            // 更改图标
            const icon = this.querySelector('i');
            if (sidebar.classList.contains('mobile-expanded')) {
                icon.classList.remove('fa-bars');
                icon.classList.add('fa-times');
            } else {
                icon.classList.remove('fa-times');
                icon.classList.add('fa-bars');
            }
        });
    }
    
    // 子菜单切换功能
    submenuItems.forEach(item => {
        const link = item.querySelector('.sidebar-nav-link');
        link.addEventListener('click', function(e) {
            // 处理不同设备上的不同行为
            if (window.innerWidth <= 768 || sidebar.classList.contains('collapsed')) {
                // 在移动设备或侧边栏收缩状态下，允许链接跳转
                const href = this.getAttribute('href');
                if (href && href !== '#') {
                    // 获取链接目标
                    const targetElement = document.querySelector(href);
                    if (targetElement) {
                        e.preventDefault();
                        // 平滑滚动到目标位置
                        window.scrollTo({
                            top: targetElement.offsetTop - 70,
                            behavior: 'smooth'
                        });
                        
                        // 移动设备上，自动关闭侧边栏
                        if (window.innerWidth <= 768) {
                            sidebar.classList.remove('mobile-expanded');
                            if (mobileNavToggle) {
                                const toggleIcon = mobileNavToggle.querySelector('i');
                                if (toggleIcon) {
                                    toggleIcon.classList.remove('fa-times');
                                    toggleIcon.classList.add('fa-bars');
                                }
                            }
                        }
                    }
                }
                return;
            }
            
            // 在桌面设备上，阻止导航事件，只处理子菜单的展开/收缩
            e.preventDefault();
            
            // 切换当前子菜单状态
            item.classList.toggle('expanded');
            const submenu = item.querySelector('.sidebar-submenu');
            submenu.classList.toggle('expanded');
            
            // 关闭其他打开的子菜单
            submenuItems.forEach(otherItem => {
                if (otherItem !== item && otherItem.classList.contains('expanded')) {
                    otherItem.classList.remove('expanded');
                    otherItem.querySelector('.sidebar-submenu').classList.remove('expanded');
                }
            });
        });
        
        // 为子菜单项添加点击事件
        const submenuLinks = item.querySelectorAll('.sidebar-submenu-link');
        submenuLinks.forEach(subLink => {
            subLink.addEventListener('click', function(e) {
                e.preventDefault(); // 阻止默认行为，自己处理跳转
                
                const href = this.getAttribute('href');
                if (href && href !== '#') {
                    // 获取链接目标
                    const targetElement = document.querySelector(href);
                    if (targetElement) {
                        // 平滑滚动到目标位置
                        window.scrollTo({
                            top: targetElement.offsetTop - 70,
                            behavior: 'smooth'
                        });
                        
                        // 移动端自动关闭侧边栏
                        if (window.innerWidth <= 768) {
                            sidebar.classList.remove('mobile-expanded');
                            if (mobileNavToggle) {
                                const icon = mobileNavToggle.querySelector('i');
                                if (icon) {
                                    icon.classList.remove('fa-times');
                                    icon.classList.add('fa-bars');
                                }
                            }
                        }
                        
                        // 移除所有活动状态
                        document.querySelectorAll('.sidebar-nav-link, .sidebar-submenu-link').forEach(link => {
                            link.classList.remove('active');
                        });
                        
                        // 设置当前项为活动状态
                        this.classList.add('active');
                        
                        // 确保父菜单项也被标记为活动状态
                        const parentItem = this.closest('.sidebar-nav-item.has-submenu');
                        if (parentItem) {
                            parentItem.classList.add('expanded');
                            const parentSubmenu = parentItem.querySelector('.sidebar-submenu');
                            if (parentSubmenu) {
                                parentSubmenu.classList.add('expanded');
                            }
                            const parentLink = parentItem.querySelector('.sidebar-nav-link');
                            if (parentLink) {
                                parentLink.classList.add('active');
                            }
                        }
                    }
                }
            });
        });
    });
    
    // 为主导航项添加点击事件
    const mainNavLinks = document.querySelectorAll('.sidebar-nav-item:not(.has-submenu) .sidebar-nav-link');
    mainNavLinks.forEach(link => {
        link.addEventListener('click', function(e) {
            e.preventDefault(); // 阻止默认行为，自己处理跳转
            
            const href = this.getAttribute('href');
            if (href && href !== '#') {
                // 获取链接目标
                const targetElement = document.querySelector(href);
                if (targetElement) {
                    // 平滑滚动到目标位置
                    window.scrollTo({
                        top: targetElement.offsetTop - 70,
                        behavior: 'smooth'
                    });
                }
            }
            
            // 移动端自动关闭侧边栏
            if (window.innerWidth <= 768) {
                sidebar.classList.remove('mobile-expanded');
                if (mobileNavToggle) {
                    const icon = mobileNavToggle.querySelector('i');
                    if (icon) {
                        icon.classList.remove('fa-times');
                        icon.classList.add('fa-bars');
                    }
                }
            }
            
            // 移除所有活动状态
            document.querySelectorAll('.sidebar-nav-link, .sidebar-submenu-link').forEach(navLink => {
                navLink.classList.remove('active');
            });
            
            // 设置当前项为活动状态
            this.classList.add('active');
        });
    });
    
    // 页面加载时根据当前URL更新侧边栏活动状态
    checkUrlHash();
    
    // 监听URL变化
    window.addEventListener('hashchange', checkUrlHash);
    
    // 监听滚动事件，更新侧边栏活动状态
    window.addEventListener('scroll', debounce(updateSidebarActiveState, 100));
}

// 更新侧边栏活动状态
function updateSidebarActiveState() {
    // 获取所有标题元素
    const sections = document.querySelectorAll('h2[id^="section-"], h3[id^="section-"]');
    
    // 没有标题元素时直接返回
    if (sections.length === 0) return;
    
    // 找到当前视窗中的标题
    let currentSection = null;
    let minDistance = Infinity;
    
    sections.forEach(section => {
        const rect = section.getBoundingClientRect();
        const distance = Math.abs(rect.top);
        
        if (distance < minDistance) {
            minDistance = distance;
            currentSection = section;
        }
    });
    
    if (!currentSection) return;
    
    // 移除所有活动状态
    document.querySelectorAll('.sidebar-nav-link, .sidebar-submenu-link').forEach(link => {
        link.classList.remove('active');
    });
    
    // 设置当前项为活动状态
    const sectionId = currentSection.id;
    const sidebarLink = document.querySelector(`.sidebar-nav-link[href="#${sectionId}"]`);
    const submenuLink = document.querySelector(`.sidebar-submenu-link[href="#${sectionId}"]`);
    
    // 先关闭所有展开的子菜单
    document.querySelectorAll('.sidebar-nav-item.has-submenu').forEach(item => {
        item.classList.remove('expanded');
        const submenu = item.querySelector('.sidebar-submenu');
        if (submenu) {
            submenu.classList.remove('expanded');
        }
    });
    
    if (sidebarLink) {
        sidebarLink.classList.add('active');
        
        // 如果是子菜单项，展开父菜单
        const parentItem = sidebarLink.closest('.sidebar-nav-item.has-submenu');
        if (parentItem) {
            parentItem.classList.add('expanded');
            const submenu = parentItem.querySelector('.sidebar-submenu');
            if (submenu) {
                submenu.classList.add('expanded');
            }
        }
    } else if (submenuLink) {
        submenuLink.classList.add('active');
        
        // 展开父菜单并激活父菜单项
        const parentItem = submenuLink.closest('.sidebar-nav-item.has-submenu');
        if (parentItem) {
            parentItem.classList.add('expanded');
            const submenu = parentItem.querySelector('.sidebar-submenu');
            if (submenu) {
                submenu.classList.add('expanded');
            }
            const parentLink = parentItem.querySelector('.sidebar-nav-link');
            if (parentLink) {
                parentLink.classList.add('active');
            }
        }
    }
}

// 防抖函数
function debounce(func, wait) {
    let timeout;
    return function() {
        const context = this;
        const args = arguments;
        clearTimeout(timeout);
        timeout = setTimeout(() => func.apply(context, args), wait);
    };
}
